package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHUtil
import org.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.sql.Timestamp
import java.text.DateFormat
import java.text.SimpleDateFormat

/**
 *
 * @Title: autoPAreallocation* @Description:平安期货导入名单分配 ,job定时每隔1分钟调用一次,页面ID：DZ9S48
 * @table: Pa_listallocation_bacth导入批次表,marketing_temporary 导入详情表
 * @author: 陶豪
 * @date 2021-12-02 10:22:00
 *
 */
public class apiKFreallocation implements ServiceBackInvoke {

    private static final Logger log = LoggerFactory.getLogger(apiKFreallocation.class);
    String inData = "";
    String outData = "";
    String calltype = "";//外呼类型
    String bathstaff = "";

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = httpServletRequest.getMethod();


        // 初始化返回参数
        String Syncpram = "";
        String Retupram = "";
        if (getMethod.equals("GET")) {
            Syncpram = httpServletRequest.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }

            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        String dataSourceID = "dataSource";
        try {
            net.sf.json.JSONObject inJson = net.sf.json.JSONObject.fromObject(Syncpram);
            calltype = inJson.getString("call_type");
            String Batch_id = inJson.getString("Batch_id");
            //拿到批次选择的回访外呼类型


            //查询是否是促开任务
            if (calltype == "4CA2PP"||calltype=='EP6LZT') {
                //查询导入详情中间表
                List marktingList = eliteBean.chaxun_sql("Select DISTINCT rec_id,batch_id,mobile,objective_guid,Staff_id,rolegroup_id,Deal_Time From marketing_temporary where Staff_id IS  NOT NULL AND result_desc IS NULL   and batch_id='" + Batch_id + "' limit 2000  ", "dataSource");
                for (int i = 0; i < marktingList.size(); i++) {
                    long startTime = System.currentTimeMillis();
                    Map marktingMap = marktingList.get(i);
                    String mobile = marktingMap.get("mobile");//手机号
                    // Batch_id = marktingMap.get("Batch_id");//批次ID
                    // String Objective_Guid = marktingMap.get("objective_guid");//obj GUID
                    String Staff_id = marktingMap.get("Staff_id");//人员ID
                    String rolegroup_id = marktingMap.get("rolegroup_id");//人员组别
                    String rec_id = marktingMap.get("rec_id");
                    String Deal_Time = marktingMap.get("Deal_Time");
                    String hsid = null;
                    if (Deal_Time != null || Deal_Time != '') {
                        // 查询名单是否已经存在
                        List custCountList = eliteBean.chaxun_sql("Select Customer_Guid From Customer Where mobile = '" + mobile + "'", "dataSource");
                        //如果没有则将批次状态改成已完成
                        log.debug("返回" + 'marktingCount');
                        //如果没有客户
                        if (custCountList.size() <= 0) {
                            //不存在新增入库
                            String Temp_Guid1 = KHUtil.getRandomString(31).toUpperCase();
                            String Customer_Guid = "CUST_" + Temp_Guid1;
                            //查询促开视图
                            List Promote_OpenList = eliteBean.chaxun_sql("select cust_mobiletelephone,creat_date,f_channel,f_xf_channel,investorid,f_cloud_state,opendate,f_register_time From dws.promote_open where 1=1 and cust_mobiletelephone='"+mobile+"' order by creat_date desc  limit 1 ", "dataSource");
                            if (Promote_OpenList.size() > 0) {
                                Map Promote_OpenMap = Promote_OpenList.get(0);
                                def  creat_date = Promote_OpenMap.get("creat_date");//预约时间
                                def f_channel = Promote_OpenMap.get("f_channel") == null ? '' : Promote_OpenMap.get("f_channel");//主渠道
                                def f_xf_channel = Promote_OpenMap.get("f_xf_channel") == null ? '' : Promote_OpenMap.get("f_xf_channel");//细分渠道
                                def zz3 = Promote_OpenMap.get("investorid") == null ? '' : Promote_OpenMap.get("investorid");//资金账号
                                def f_cloud_state = Promote_OpenMap.get("f_cloud_state") == null ? '' : Promote_OpenMap.get("f_cloud_state");//云平台状态
                                def zz4 = Promote_OpenMap.get("opendate") == null ? '' : Promote_OpenMap.get("opendate");//开户时间
                                def f_register_time = Promote_OpenMap.get("f_register_time");//注册时间

                                log.debug("打印[手机号:]" + mobile + "[预约时间:]" + creat_date + "[主渠道:]" + f_channel + "[细分渠道:]" + f_xf_channel);
                                log.debug("预约时间：" + creat_date + "注册时间:" + f_register_time);
                                // def  s1= f_register_time.toString().substring(0,f_register_time.toString().length()-2);
                                eliteBean.update("insert into customer(customer_guid,mobile,appointment_time,channel,f_xf_channel,f_cloud_state,open_account,customer_id)values('" + Customer_Guid + "','" + mobile + "','"+creat_date+"','"+f_channel+"','"+f_xf_channel+"','"+f_cloud_state+"','"+zz4+"','"+zz3+"') ", "dataSource");
                                //查找Objective 表是否有同任务类型
                                List ObjCountList = eliteBean.chaxun_sql("select Customer_Guid,HANDLEGROUP_ID,HANDLEBY_ID FROM Objective WHERE MAP_ID='" + calltype + "' and CUSTOMER_GUID='" + Customer_Guid + "' ", "dataSource");
                                if (ObjCountList.size() <= 0) {
                                    //新任务类型新增入库
                                    newCustomerDeal(eliteBean, rolegroup_id, Staff_id, calltype, Customer_Guid, hsid, Batch_id, rec_id, bathstaff);
                                } else {
                                    //该客户已有同类型的任务，失败数+1
                                    eliteBean.update("Update Pa_listallocation_bacth Set  lose_num=lose_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                                    log.debug("分配失败！");
                                    //修改中间表  result_Desc='分配失败,任务类型已存在'    result_code='-3'
                                    eliteBean.update("Update marketing_temporary Set result_code='-3',result_Desc='分配失败,该客户已存在任务类型',Deal_Time=now() where batch_id='" + Batch_id + "' and rec_id='" + rec_id + "' ", "dataSource");
                                }
                            }else{
                                eliteBean.update("insert into customer(customer_guid,mobile, CREATEDBY,CREATEDDATE)values('" + Customer_Guid + "','" + mobile + "','000116',now()) ", "dataSource");
                                //查找Objective 表是否有同任务类型
                                List ObjCountList = eliteBean.chaxun_sql("select Customer_Guid,HANDLEGROUP_ID,HANDLEBY_ID FROM Objective WHERE MAP_ID='" + calltype + "' and CUSTOMER_GUID='" + Customer_Guid + "' ", "dataSource");
                                if (ObjCountList.size() <= 0) {
                                    //新任务类型新增入库
                                    newCustomerDeal(eliteBean, rolegroup_id, Staff_id, calltype, Customer_Guid, hsid, Batch_id, rec_id, bathstaff);
                                } else {
                                    //该客户已有同类型的任务，失败数+1
                                    eliteBean.update("Update Pa_listallocation_bacth Set  lose_num=lose_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                                    log.debug("分配失败！");
                                    //修改中间表  result_Desc='分配失败,任务类型已存在'    result_code='-3'
                                    eliteBean.update("Update marketing_temporary Set result_code='-3',result_Desc='分配失败,该客户已存在任务类型',Deal_Time=now() where batch_id='" + Batch_id + "' and rec_id='" + rec_id + "' ", "dataSource");
                                }
                            }

                        } else {
                            Map custCountMap=custCountList.get(0);
                            String custguid=custCountMap.get("Customer_Guid");
                            //用户存在则 查找Objective 表是否有同任务类型
                            List ObjCountList = eliteBean.chaxun_sql("select Customer_Guid,HANDLEGROUP_ID,HANDLEBY_ID FROM Objective WHERE MAP_ID='" + calltype + "' and CUSTOMER_GUID='" + custguid + "' ", "dataSource");
                            if (ObjCountList.size() <= 0) {

                                //新任务类型新增入库
                                newCustomerDeal(eliteBean, rolegroup_id, Staff_id, calltype, custguid, hsid, Batch_id, rec_id, bathstaff);
                            } else {
                                //该客户已有同类型的任务，失败数+1
                                eliteBean.update("Update Pa_listallocation_bacth Set  lose_num=lose_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                                log.debug("分配失败！");
                                //修改中间表  result_Desc='分配失败,任务类型已存在'    result_code='-3'
                                eliteBean.update("Update marketing_temporary Set result_code='-3',result_Desc='分配失败,该客户已存在任务类型',Deal_Time=now() where batch_id='" + Batch_id + "' and rec_id='" + rec_id + "' ", "dataSource");
                            }
                        }
                    }

                }

                //----------------------------------------------------------------回访类型-----------------------------------------------------------------
            } else {
                //查询导入详情中间表
                List marktingList = eliteBean.chaxun_sql("Select DISTINCT rec_id,batch_id,hsid,objective_guid,Staff_id,rolegroup_id,Deal_Time From marketing_temporary where Staff_id IS  NOT NULL AND result_desc IS NULL  and batch_id='" + Batch_id + "' limit 3000  ", "dataSource");
                for (int i = 0; i < marktingList.size(); i++) {
                    long startTime = System.currentTimeMillis();
                    Map marktingMap = marktingList.get(i);
                    String hsid = marktingMap.get("hsid");//资金账号
                    Batch_id = marktingMap.get("Batch_id");//批次ID
                    String Objective_Guid = marktingMap.get("objective_guid");//obj GUID
                    String Staff_id = marktingMap.get("Staff_id");//人员ID
                    String rolegroup_id = marktingMap.get("rolegroup_id");//人员组别
                    String rec_id = marktingMap.get("rec_id");
                    String Deal_Time = marktingMap.get("Deal_Time");
                    if (Deal_Time != null || Deal_Time != '') {
                        // 查询名单是否已经存在
                        List custCountList = eliteBean.chaxun_sql("Select Customer_Guid From Customer Where Customer_Id = '" + hsid + "'", "dataSource");

                        //如果没有则将批次状态改成已完成
                        log.debug("返回" + 'marktingCount');
                        if (custCountList.size() > 0) {
                            Map custMap = custCountList.get(0);
                            String custguid = custMap.get("Customer_Guid");
                            //查找Objective 表是否有同任务类型
                            List ObjCountList = eliteBean.chaxun_sql("select Customer_Guid,HANDLEGROUP_ID,HANDLEBY_ID FROM Objective WHERE MAP_ID='" + calltype + "' and CUSTOMER_GUID='" + custguid + "' ", "dataSource");
                            if (ObjCountList.size() <= 0) {
                                //新任务类型新增入库
                                newCustomerDeal(eliteBean, rolegroup_id, Staff_id, calltype, custguid, hsid, Batch_id, rec_id, bathstaff);
                            } else {
                                //该客户已有同类型的任务，失败数+1
                                eliteBean.update("Update Pa_listallocation_bacth Set  lose_num=lose_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                                log.debug("分配失败！");
                                //修改中间表  result_Desc='分配失败,任务类型已存在'    result_code='-3'
                                eliteBean.update("Update marketing_temporary Set result_code='-3',result_Desc='分配失败,该客户已存在任务类型',Deal_Time=now() where batch_id='" + Batch_id + "' and rec_id='" + rec_id + "' ", "dataSource");
                            }
                        } else {
                            //该客户不在系统内，失败数+1
                            eliteBean.update("Update Pa_listallocation_bacth Set  lose_num=lose_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                            log.debug("分配失败！");
                            //修改中间表  result_Desc='分配失败,该客户不存在'    result_code='-1'
                            eliteBean.update("Update marketing_temporary Set result_code='-1',result_Desc='分配失败,该客户不存在',Deal_Time=now() where batch_id='" + Batch_id + "' and rec_id='" + rec_id + "'", "dataSource");
                        }
                    }
                }




                //查询还有没有待分配的名单------------------------

            }




        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
            log.debug("处理完成返回结果:" + outData);
            return outData
        }

    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;

    }

    /**
     * 新任务类型客户入库
     * @param eliteBean
     * @param R 、
     * @return
     */
    public static boolean newCustomerDeal(EliteBean eliteBean, String r_Rolegroup_Id, String r_Staff_Id, String task_type, String Customer_guid, String Customerid, String Batch_id, String rec_id,String bathstaff) {
        boolean reFlag = true;
        try {

            /**
               // 查询是否存在除了经营之外的任务 ,如果有则将组别 人员  赋值给该任务的组别 人员
             List ApwList=eliteBean.chaxun_sql("Select HANDLEGROUP_ID,HANDLEBY_ID From elitetask where map_id!='M4F19B' AND CUSTOMER_GUID='"+Customer_guid+"' LIMIT 1  ","dataSource");
             if(ApwList.size()>0){
             r_Rolegroup_Id=ApwList.get(0).get("HANDLEGROUP_ID");
             r_Staff_Id=ApwList.get(0).get("HANDLEBY_ID");
             log.debug("本次导入任务分配给人员："+r_Staff_Id+"---组别："+r_Rolegroup_Id);
             }
             **/




            // 生成相关ID
            String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
            //   String Customer_Guid = "CUST_" + Temp_Guid;
            String Objective_Guid = "OBJE_" + Temp_Guid;
            String EliteTask_Guid = "TASK_" + Temp_Guid;
            String[] custTaskDealSQL = new String[6];
            // 插入Objective表
            custTaskDealSQL[1] = "Insert Into Objective" +
                    "  (Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Priority_Id," +
                    "   Expireddate," +
                    "   Customer_Guid," +
                    "   Objectivestatus," +
                    "   Iscontact," +
                    "   Trytimes," +
                    "   Successfulcontacttimes," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Obstatus," +
                    "   Failure_Attempt," +
                    "   Contact_Customer_Guid," +
                    "   Passflag," +
                    "   Lastassigndate," +
                    "   Failstatus," +
                    "   Successstatus," +
                    "   Owner," +
                    "   Workorderframe_Id," +
                    "   Category," +
                    "   Forecastdate," +
                    "   Workorderid," +
                    "   Workordertype1," +
                    "   Workordertype2," +
                    "   Workordertype3," +
                    "   Workordertype4," +
                    "   Objectivesubstatus," +
                    "   Map_Id," +
                    "   Curstep_Id_Map," +
                    "   Max_Attempt," +
                    "   Nocontacttry," +
                    "   Allocation_Pool," +
                    "   Appointment," +
                    "   PA_TASKTYPE,CUSTLISTNAME)" +
                    "Values" +
                    "  ('" + Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'NORMAL'," +
                    "   Date_Add(Now(), Interval 1 Day)," +
                    "   '" + Customer_guid + "'," +
                    "   'OPEN'," +
                    "   0," +
                    "   0," +
                    "   0," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   'OPEN'," +
                    "   999," +
                    "   ''," +
                    "   0," +
                    "   Null," +
                    "   '0'," +
                    "   '0'," +
                    "   ''," +
                    "   '" + task_type + "'," +
                    "   'CASE'," +
                    "   '2021-04-25 17:59:35'," +
                    "   Concat('HS', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
                    "   'QL800E'," +
                    "   'O7JIUV'," +
                    "   ''," +
                    "   ''," +
                    "   'OPEN'," +
                    "   '" + task_type + "'," +
                    "   'ONA0KD'," +
                    "   0," +
                    "   0," +
                    "   0," +
                    "   0,'" + task_type + "','"+Batch_id+"')";

            // 插入EliteTask表
            custTaskDealSQL[2] = "Insert Into Elitetask" +
                    "  (Elitetask_Guid," +
                    "   Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Expectstarttime," +
                    "   Expectendtime," +
                    "   Obstatus," +
                    "   Recordstatus," +
                    "   Attempt," +
                    "   Max_Attempt," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Failure_Attempt," +
                    "   Comments," +
                    "   Customer_Guid," +
                    "   Localtrycount," +
                    "   Lastassigndate," +
                    "   Workorderframe_Id," +
                    "   Curstepstatus," +
                    "   Curstep_Id," +
                    "   Stepforecastdate," +
                    "   Curstep_Id_Map," +
                    "   Map_Id," +
                    "   Objectivesubstatus," +
                    "   Elitetaskstatus," +
                    "   Obflag,Maintaskstep_Id_Map,PA_TASKTYPE,CUSTLISTNAME)" +
                    "Values" +
                    "  ('" + EliteTask_Guid + "'," +
                    "   '" + Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   Now()," +
                    "   Date_Add(Now(), Interval 3 Day)," +
                    "   'OPEN'," +
                    "   0," +
                    "   0," +
                    "   999," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   999," +
                    "   ''," +
                    "   '" + Customer_guid + "'," +
                    "   0," +
                    "   Now()," +
                    "   ''," +
                    "   'OPEN'," +
                    "   'ONA0KD'," +
                    "   Now()," +
                    "   'ONA0KD'," +
                    "   '" + task_type + "'," +
                    "   'OPEN'," +
                    "   'OPEN'," +
                    "   1,'ONA0KD','" + task_type + "','"+Batch_id+"')";
            //写入顾问分配历史表
            custTaskDealSQL[3] = "insert into hst_Service_hislist (sys_guid,CUSTOMER_ID,customer_guid,used_staffid,apply_time,MODIFIEDBY,context,Reviewer_staffid,Reviewer_time)values(UUID(),'" + Customerid + "','" + Customer_guid + "','" + r_Staff_Id + "',now(),'" + 'SELITE' + "','导入名单分配','"+bathstaff+"',now())";
            //分配成功 则修改批次表 成功数+1
            custTaskDealSQL[4] = "Update Pa_listallocation_bacth Set  succeed_num=succeed_num+1 where batch_id='" + Batch_id + "' ";
            //修改中间表  result_Desc='分配成功!'    result_code='1'
            custTaskDealSQL[5] = "Update marketing_temporary Set result_code='1',result_Desc='分配成功!',Deal_Time=now() where batch_id='" + Batch_id + "' and rec_id='" + rec_id + "'";

            log.debug("分配成功！");
            int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");

            //判断批次是否执行完毕
            List iscount=eliteBean.chaxun_sql("select * from marketing_temporary where  1=1 and  Deal_Time is null  and batch_id='" + Batch_id + "'", "dataSource");
            if (iscount.size()<=0){
                eliteBean.update("Update Pa_listallocation_bacth Set batch_state='1' where batch_id='" + Batch_id + "'", "dataSource");
            }

            log.debug("新客户入库批量处理SQL返回结果：" + batchSQLResult.toString());
        } catch (Exception e) {
            log.error("新客户入库异常!", e);
            reFlag = false;
        }
        return reFlag;
    }

}
